<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>组织架构</el-breadcrumb-item>
      <el-breadcrumb-item>部门列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-form :inline="true" :model="addDepartForm" label-position="right" label-width="80px" :rules="addDepartFormRules" ref="addDepartFormRef" size="small">
        <el-form-item label="上级部门" prop="parent_id">
          <el-cascader v-model="addDepartForm.parent_id" :options="departListData" :props="selectDepartProps" clearable @change="selectDepartValueChange"></el-cascader>
        </el-form-item>
        <el-form-item label="部门名称" prop="departname">
          <el-input v-model="addDepartForm.departname"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addDepart">添加</el-button>
          <el-button type="warning" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-table :data="departListData" border row-key="id" stripe style="width: 100%" size="mini">
        <el-table-column prop="departname" label="部门名称" width="150" align="left" header-align="center"></el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-button @click="editDepart(scope.row)" type="primary" size="mini" class="tableRowButton">编辑</el-button>
            <el-popover placement="top" width="80" :ref="`popover-${scope.$index}`">
              <p>
                确定要删除部门 <b>{{ scope.row.departname }}</b> 吗？
              </p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="cancelAction(scope)">取消</el-button>
                <el-button type="primary" @click="delDepart(scope)" size="mini">确定</el-button>
              </div>
              <el-button slot="reference" type="danger" size="mini">删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="编辑部门" :visible.sync="dialogDepartEditFormVisible">
      <el-form :model="departEditForm" size="small" label-width="80px" label-position="right">
        <el-form-item label="部门名称">
          <el-input v-model="departEditForm.departname" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSaveDepart" size="small">保 存</el-button>
        <el-button @click="dialogDepartEditFormVisible = false" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addDepartForm: {
        parent_id: 0,
        departname: ''
      },
      addDepartFormRules: {
        parent_id: [],
        departname: [
          { max: 17, message: '长度不大于17个字符', trigger: 'blur' },
          { required: true, message: '请填写部门名称', trigger: 'blur' }
        ]
      },
      departListData: [],
      total: 0,
      departEditForm: {},
      idArr: [],
      selectDepartProps: {
        label: 'departname',
        value: 'id',
        checkStrictly: true,
        emitPath: false
      },
      dialogDepartEditFormVisible: false
    }
  },
  created() {
    this.getDepart()
  },
  methods: {
    // 添加部门
    addDepart() {
      this.$refs.addDepartFormRef.validate(async (valid) => {
        if (valid === false) return false
        // 添加部门方法
        console.log(this.addDepartForm)
        const { data: res } = await this.$http.post('api/org/depart', this.addDepartForm)
        if (res.code !== 0) return this.$message.error('添加部门失败！')
        this.$message.success('添加成功！')
        this.getDepart()
      })
    },
    // 选中上级部门发生变化时
    selectDepartValueChange(val) {
      if (val === null) {
        this.addDepartForm.parent_id = 0
      }
    },
    // 重置
    resetForm() {
      this.$refs.addDepartFormRef.resetFields()
    },
    // 获取部门
    async getDepart() {
      const { data: res } = await this.$http.get('api/org/depart', { params: this.queryInfo })
      this.departListData = res.data
      this.total = res.total
      console.log(this.departListData)
    },
    // 编辑部门
    editDepart(row) {
      this.departEditForm = JSON.parse(JSON.stringify(row))
      console.log(this.departEditForm)
      this.dialogDepartEditFormVisible = true
    },
    async editSaveDepart() {
      const { data: res } = await this.$http.put(`/api/org/depart/${this.departEditForm.id}`, { departname: this.departEditForm.departname })
      if (res.code !== 0) return this.$message.error('保存失败！')
      this.$message.success('保存成功！')
      this.dialogDepartEditFormVisible = false
      this.getDepart()
    },
    // 删除
    async delDepart(scope) {
      this.idArr = []
      // 获取当前部门及其子部门的id
      this.getDepId(scope.row)
      const { data: res } = await this.$http.delete('/api/org/depart', { data: this.idArr })
      if (res.code !== 0) return this.$message.error('删除失败！')
      this.$message.success('删除成功！')
      scope._self.$refs[`popover-${scope.$index}`].doClose()
      this.getDepart()
    },
    // 取消操作
    cancelAction(scope) {
      scope._self.$refs[`popover-${scope.$index}`].doClose()
    },
    // 递归返回数据里面所有的id，包含children中的id
    getDepId(data) {
      if (!data.children) {
        this.idArr.push(parseInt(data.id))
      } else {
        this.idArr.push(parseInt(data.id))
        data.children.forEach((item) => {
          this.getDepId(item)
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.tableRowButton {
  margin-right: 5px;
}
</style>
